package main

import (
	"context"
	"database/sql"
	"github.com/casbin/casbin"
	_ "github.com/go-sql-driver/mysql"
	"log"
	"net/http"
	"route/rbac"
	rbacmdl "route/rbac/middleware"
)

var (
	rbacModel = "config/casbin/rbac_model.conf"
)

func main() {
	mydb, err := sql.Open("mysql", "root:password@tcp(172.17.0.5:3306)/mydb")
	if err != nil {
		log.Fatalln(err.Error())
	}
	defer mydb.Close()

	a, err := adapter.NewAdapter(mydb)
	if err != nil {
		log.Fatalln(err.Error())
	}
	e := casbin.NewEnforcer(rbacModel, a)
	if e == nil {
		log.Fatalln(err.Error())
	}

	e.LoadPolicy()
	defer e.SavePolicy()

	mdl := rbacmdl.NewMiddleware(e)

	server := http.Server{
		Addr: ":http",
		Handler: preMdl(
			mdl.Authenticate(&rbacmdl.Operation{
				Object: "object",
				Action: "action",
			})(
				http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
					w.Write([]byte("Hello"))
				}))),
	}

	server.ListenAndServe()
}

func preMdl(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 给 rbac middleware 的前缀中间件
		urlQuery := r.URL.Query()
		value := urlQuery.Get("key")
		r = r.WithContext(context.WithValue(context.Background(), rbacmdl.Subject, value))

		next.ServeHTTP(w, r)
	})
}
